import { computed, ref } from 'vue'
export const useFocusHook = (data, callback) => {

  const selectIndex = ref(-1)

const lastSelectBlock = ref(null)

  // 清空其他的block的focus
  const clearBlockFocus = () => {
    data.value.blocks.forEach((item) => {
      if (item.focus) {
        item.focus = false
      }
    })
    selectIndex.value = -1
  }

  const deletSelectBlock = (e) => {
    if (e.key === 'Delete') {
      const blocks = data.value.blocks
      blocks.splice(selectIndex.value, 1)
      data.value = { ...data.value, blocks }
      clearBlockFocus()
    }
  }

  // 获取元素焦点
  const blockMouseDown = (e, block, index) => {

    // 监听键盘按下事件
    window.addEventListener('keydown', deletSelectBlock)

    selectIndex.value = index // 存储当前选中的index

    lastSelectBlock.value = data.value.blocks[selectIndex.value]

    // 阻止默认行为
    e.preventDefault()
    // 防治事件冒泡
    e.stopPropagation()

    // 如果按下了shift
    if (e.shiftKey) {
      block.focus = !block.focus
    } else {
      if (!block.focus) {
        clearBlockFocus()
        block.focus = true
      }
    }
    callback(e)
  }

  const focusData = computed(() => {
    const focus = []
    const unfocus = []
    data.value.blocks.forEach((item) => {
      if (item.focus) {
        focus.push(item)
      } else {
        unfocus.push(item)
      }
    })

    return { focus, unfocus }
  })

  return {
    blockMouseDown,
    focusData,
    clearBlockFocus,
    lastSelectBlock,
  }
}
